package com.wyh.service.serviceImpl.feemanagementserviceimpl;


import com.wyh.domain.po.feemanagementpo.BillingItemss;
import com.wyh.domain.po.feemanagementpo.PreStorages;
import com.wyh.mapper.feemanagementmapper.PrestorageMapper;
import com.wyh.service.feemanagementservice.IPrestorageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;


/**
 * <p>
 * 预存账户表 服务实现类
 * </p>
 *
 * @author ggt
 * @since 2024-05-23
 */
@Service("g3PrestorageServce")
public class PrestorageServiceImpl extends ServiceImpl<PrestorageMapper, PreStorages> implements IPrestorageService {

    @Autowired
    PrestorageMapper prestorageMapper;

    //资源对应预存
    @Override
    public BigDecimal getPrestorageByResourceId(Integer resourceId, Integer specialName) {
        BigDecimal afterchange = new BigDecimal(0);
        //通过resourceid查询subject
        List<PreStorages> list = lambdaQuery().eq(PreStorages::getResourceid, resourceId).list();
        for (PreStorages preStorages : list) {
            //通过subject查询billingitems
            BillingItemss billingitems = prestorageMapper.getbillingitemById(preStorages.getSubject());
            //通过billingitems查询specialName
            Integer specialName1 = billingitems.getSpecialName();
            if (specialName1 == specialName) {
                afterchange = preStorages.getAfterchange();
            }
        }
        return afterchange;
    }

    @Override
    //通过subject查询预存
    public BigDecimal getPrestorageBySubject(Integer billingitemsid, BigDecimal sumAmount) {
        BigDecimal afterchange = lambdaQuery().eq(PreStorages::getSubject, billingitemsid).one().getAfterchange();
        BigDecimal yue = afterchange.subtract(sumAmount);

        BigDecimal sum = new BigDecimal(0);
        if(yue.compareTo(BigDecimal.ZERO) >= 0){
            boolean update1 = lambdaUpdate()
                    .set(PreStorages::getBeforechange, afterchange)
                    .set(PreStorages::getAfterchange, yue)
                    .set(PreStorages::getOperationtime, System.currentTimeMillis())
                    .update();
            sum = BigDecimal.ZERO;
        }else {
            boolean update2 = lambdaUpdate()
                    .set(PreStorages::getBeforechange, afterchange)
                    .set(PreStorages::getAfterchange, BigDecimal.ZERO)
                    .set(PreStorages::getOperationtime, System.currentTimeMillis())
                    .update();
            sum = sumAmount.subtract(afterchange);
        }
        return sum;
    }
    @Override
    public BigDecimal getPrestorageBySubject(Integer billingitemsid){
        BigDecimal afterchange = lambdaQuery().eq(PreStorages::getSubject, billingitemsid).one().getAfterchange();
        return afterchange;
    }
}
